<?php
/**
 * 房间相关接口
 */

namespace App\Http\Controllers\App\V1;

use App\Enums\MallEnum;
use App\Enums\UserEnum;
use App\Models\MainDB\Streamer\StreamerLevel;
use App\Models\MainDB\UserData;
use App\Models\MainDB\UserRoom;
use App\Services\Tools\MapService;
use Carbon\Carbon;
use App\Response\Response;
use App\Services\Tools\PushService;
use App\Services\Tools\RedisService;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use App\Repositories\GiftHallRepository;
use App\Enums\RedisKeyEnum;

//引用http请求类
use App\Exceptions\BasicException;

//引入框架异常处理类

class RoomController extends BaseController
{
    /**
     * @api {post} /api/room/user 7,房间用户资料卡
     * @apiVersion 0.1.0
     * @apiName 房间用户资料卡
     * @apiGroup 房间模块
     *
     * @apiParam {string} user_id   用户id,必传
     * @apiParam {string} room_id   房间id,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "user_id": 547900,
     * "user_code": 617040,
     * "nickname": "ti mo o o",
     * "head_picture": "",
     * "rank_id": 50,
     * "nobility_id": 5,
     * "emchat_username": "18658172093",
     * "rank_icon": "",
     * "nobility_icon 爵位小图标": "",
     * "nobility_picture 爵位图片": "",
     * "good_number 是否靓号1是0否": 0,
     * "shutup 是否禁麦1是2否": 2,
     * "role 1房主2管理3普通4主持5官方": 2,
     * "banned 1禁言0不禁言": 1,
     * "follow 1已关注0未关注": 0,
     * "nobility_set 爵位背景样式设置": {
     * "color_from": "#E4D3FF",
     * "color_to": "#C5A0FF",
     * "txt_color": "#5642B3",
     * "head_color": "#E3D1FF"
     * },
     * "pit_number 当前麦位": 9,
     * "show_push_btn 是否显示推送按钮1显示0不显示": 0,
     * "show_order_btn 是否显示下单按钮1显示0不显示": 0,
     * "special": {
     * "avatar 头像挂件": {
     * "material": ""
     * },
     * "nickname 昵称挂件": {
     * "material": ""
     * },
     * "nickname_special 昵称特效": {
     * "material": ""
     * },
     * "ride 坐骑": {
     * "material": "",
     * "show_type 1公屏2全屏3右侧": 1
     * },
     * "join 进入房间": {
     * "color": "#ffffff",
     * "material": "",
     * "show_type 1老版本2新版本": 1
     * },
     * "chat 私聊": {
     * "material": ""
     * },
     * "chatroom 公聊": {
     * "material": ""
     * },
     * "wave 声波": {
     * "material": ""
     * },
     * "broadcast 广播": {
     * "material": ""
     * }
     * }
     * }
     * }
     */
    public function userInfo(Request $request)
    {
        $user_id = $request->input('user_id');
        $room_id = $request->input('room_id');
        if ($room_id <= 0) {
            throw new BasicException(40002);
        }
        if ($user_id <= 0) {
            throw new BasicException(40014);
        }

//        $room_info = app('model_user_room')->getRoomDetail($room_id);
        $room_info = RedisService::getRoomDetailByRoomId($room_id);
        if (!$room_info) {
            throw new BasicException(40002);
        }

//        $user = app('model_user')->getUserDetail($user_id);
        $user = RedisService::getUserBaseInfo($user_id);
        if (!$user) {
            throw new BasicException(40014);
        }
        if ($user['role'] == 5) {//官方
            $role = 5;
        } elseif ($room_info['user_id'] == $user_id) {
            $role = 1;//房主
        } elseif (RedisService::checkRoomManager($room_id, $user_id)) {
            $role = 2;//管理
        } elseif ($room_info['holder'] == $user_id) {
            $role = 4;//主持
        } else {
            $role = 3;
        }


        $info = app('model_follow')->getUserFollow(UID, $user_id);

        //查看用户现在是否在麦位上 todo
        $pit_info_now = app('model_room_pit')->getPitUser($room_id, $user_id);
        $pit_number = isset($pit_info_now->pit_number) && $pit_info_now->pit_number > 0 ? $pit_info_now->pit_number : 0;
        /*if ($pit_number == 0 && UserRoom::query()->where(['permanent_user_id' => $user_id, 'room_id' => $room_id])->exists()) {
            $pit_number = 1;
        }*/
        //是否禁言
        $banned = app('model_room_banned')->getRoomBannedUser($room_id, $user_id);
        //公会铭牌
        $sociatyBadge = MapService::userSociatyBadge($user_id);
        // 是否在房间黑名单
        /*$inRoomBanned = app('model_room_blacklist')
            ->newQuery()
            ->where("black_id", $user_id)
            ->where("room_id", $room_id)
            ->exists();*/
        $inRoomBanned = app('redis')->zrank(sprintf(RedisKeyEnum::ROOM_BLACK_LIST, $room_id), $user_id);
        //用户主播等级图标
//        $streamLevelIcon = StreamerLevel::query()->where(['level' => $user['user_data']['streamer_level']])->value('icon');
        $streamLevelIcon = '';


        $special = app('model_user')->special($user_id);
        #爵位名片框
        $nobility_card_frame = $special['card_frame']['material'];

        $return_data = [
            'user_id' => $user['user_id'],
            'user_code' => $user['user_code'],
            'nickname' => $user['nickname'],
            'signature' => $user['signature'],
            'sociaty_badge' => [
                "name" => $sociatyBadge['name'] ?? "",
                "img" => $sociatyBadge['img'] ?? "",
            ],
            'head_picture' => $user['head_picture'],
            'rank_id' => $user['rank_id'],
            'sociaty_name' => RedisService::setGuildUser($user_id) ?: '',
            'nobility_id' => $user['nobility'],
            'emchat_username' => $user['emchat_username'],
            'rank_icon' => app('model_grade_config')->getGradeIcon($user['rank_id']),
            'charm_icon' => app('model_charm_config')->getCharmIcon($user['charm_id']),
            'nobility_icon' => app('model_nobility')->getNobilityIcon($user['nobility']),
            'nobility_picture' => app('model_nobility')->getNobilityImage($user['nobility']),
            'nobility_card_frame' => $nobility_card_frame,
            'good_number' => checkGoodNumber($user['user_code']),
            'shutup' => $pit_info_now->shutup ?? 2,
            //是否禁麦1是2否
            'role' => $role,
            //1房主2管理3普通4主持5官方
            'banned' => $banned ? 1 : 0,
            'follow' => $info ? 1 : 0,
            'nobility_set' => app('model_nobility')->nobilityDisplaySet($user['nobility']),
            'pit_number' => $pit_number,
            'show_push_btn' => 0,
            'special' => $special,
            'in_room_banned' => (int)$inRoomBanned,
            'streamer_level_icon' => $streamLevelIcon ?? '',
            #'gender' => $user['sex'] ?? UserData::query()->where(['user_id' => $user['user_id']])->value('sex'),
            'sex'   => $user['sex'],
            'age'   => birthToAge($user['birthday'], true),
            'title_gift_info' => app('repo_user')->getUserTitleNowInfo($user['user_id']),
            'recharge_icon' => RedisService::getUserRechargeIcon($user['user_id']),
            //1显示推送按钮0不显示
        ];



        //获取展馆
        /*$giftListIds = GiftHallRepository::getInstance()->getWallGift(); //礼物墙礼物
        $hallListMap = GiftHallRepository::getInstance()->getAllHall(); //所有展馆
        $hallToGift = GiftHallRepository::getInstance()->getHallGift(array_keys($hallListMap), $giftListIds);
        $userHallRecordMap = GiftHallRepository::getInstance()->getUserHallRecord($user_id); //展馆记录
        $userGiftIds = GiftHallRepository::getInstance()->getUserGetAllGift($user_id); //获取的礼物

        $hallBg = app('model_config')->getValue('GIFT_HALL_DEFAULT_IMG');
        foreach ($hallListMap as $hall_id => $hallDetail) {
            if (!isset($hallToGift[$hall_id])) {  //如果展馆添加的礼物没有礼物墙的
                unset($hallListMap[$hall_id]);
                continue;
            }
            $hallListMap[$hall_id]['total_number'] = count($hallToGift[$hall_id]);
            $status = $userHallRecordMap[$hall_id]['status'] ?? 0;

            $number = $userHallRecordMap[$hall_id]['number'] ?? 0;
            $num = $status == 2 ? intval($number / 10) : $number;

            $hallListMap[$hall_id]['status'] = $status;
            $hallListMap[$hall_id]['number'] = $num;
            $hallListMap[$hall_id]['bg_img'] = $status == 0 ? $hallBg : ($status == 1 ? $hallDetail['lower_bg'] : ($hallDetail['high_bg'] ?: $hallDetail['lower_bg']));
            $hallListMap[$hall_id]['icon_img'] = $status == 0 ? $hallDetail['default_picture'] : ($status == 1 ? $hallDetail['lower_picture'] : ($hallDetail['high_picture'] ?: $hallDetail['lower_picture']));
            $hallListMap[$hall_id]['icon_frame'] = $status == 0 ? $hallDetail['lower_frame'] : ($status == 1 ? $hallDetail['lower_frame'] : ($hallDetail['high_frame'] ?: $hallDetail['lower_frame']));

            $getCount = 0;
            foreach ($hallToGift[$hall_id] as $g) {
                if (in_array($g, $userGiftIds)) {
                    $getCount++;
                }
            }
            $hallListMap[$hall_id]['get_number'] = $getCount;
        }
        $return_data['hall'] = array_values($hallListMap);*/
        $return_data['hall'] = [];


        return Response::sendData($return_data);
    }

    /**
     * @api {get} /api/room/wheat/water B,麦位流水
     * @apiVersion 0.1.0
     * @apiName 麦位流水
     * @apiGroup 房间模块
     *
     * @apiParam {int} room_id   房间id,必传
     * @apiParam {string} time_start   开始时间Y-m-d H:i:s,必传
     * @apiParam {string} time_end   结束时间Y-m-d H:i:s,必传
     *
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": [
     * {
     * "pit_name": "主持麦",
     * "total": 0
     * },
     * {
     * "pit_name": "1",
     * "total": 0
     * },
     * {
     * "pit_name": "2",
     * "total": 0
     * },
     * {
     * "pit_name": "3",
     * "total": 0
     * },
     * {
     * "pit_name": "4",
     * "total": 0
     * },
     * {
     * "pit_name": "5",
     * "total": 0
     * },
     * {
     * "pit_name": "6",
     * "total": 0
     * },
     * {
     * "pit_name": "7",
     * "total": 0
     * },
     * {
     * "pit_name": "8",
     * "total": 0
     * }
     * ]
     * }
     * * @apiError 10010 参数校验错误
     * * @apiError 40023 只能查询14天内的流水
     * * @apiError 40024 起止时间相等
     * * @apiError 40025 结束时间小于起始时间，请重试
     */
    public function wheatWater(Request $request)
    {
        $room_id = $request->input('room_id');
        $time_start = $request->input('time_start');
        $time_end = $request->input('time_end');
        $pit_number = $request->input('pit_number', 0);
        if ($room_id <= 0 || !$time_start || !$time_end) {
            throw new BasicException(10010);
        }
        $time_start_timestamp = strtotime($time_start);
        $time_end_timestamp = strtotime($time_end);
        if ($time_start_timestamp <= 0 || $time_start_timestamp <= Carbon::now()->subDay(14)->timestamp) {
            throw new BasicException(40023);
        }
        if ($time_end_timestamp == $time_start_timestamp) {
            throw new BasicException(40024);
        }
        if ($time_end_timestamp < $time_start_timestamp) {
            throw new BasicException(40025);
        }

        $result = app('repo_room')->getWheatWater($room_id, $time_start_timestamp, $time_end_timestamp, $pit_number);

        return Response::sendData($result);
    }

    public function oneWater(Request $request)
    {
        $room_id = $request->input('room_id');
        $pit_number = $request->input('pit_number');
        $perPage = (int)$request->input('per_page', 10);
        $page = (int)$request->input('page', 1);
        $v = app('validator')->make(
            $request->all(),
            [
                'room_id' => 'required',
                'pit_number' => 'required',
            ]
        );
        if ($v->fails()) {
            throw new BasicException(10010, getValidateMessage($v->messages()));
        }
        try {
            $result = app('repo_room')->getOneWater($room_id, $pit_number, $perPage, $page);
        } catch (BasicException $e) {
            return Response::sendData($e->getMessage());
        }
        return Response::sendData($result);
    }

}
